class Steps {
  constructor(wizard) {
    this.wizard = wizard;
    this.steps = this.getSteps();
    this.stepsQuantity = this.getStepsQuantity();
    this.currentStep = 0;
  }

  setCurrentStep(currentStep) {
    this.currentStep = currentStep;
  }

  getSteps() {
    return this.wizard.getElementsByClassName('step');
  }

  getStepsQuantity() {
    return this.getSteps().length;
  }

  handleConcludeStep() {
    var host = document.getElementById("host").value;
    var username = document.getElementById("username").value;
    var userpass = document.getElementById("userpass").value;
    var name = document.getElementById("name").value;

    if (host == '' || username == '' || userpass == '' || name == '') {
      alert("数据库信息请填写完整")
      return;
    }

    if (forward) {
      this.steps[this.currentStep].classList.add('-completed');
    }

  }

  handleStepsClasses(movement) {
    if (movement > 0)
      this.steps[this.currentStep - 1].classList.add('-completed');
    else
    if (movement < 0)
      this.steps[this.currentStep].classList.remove('-completed');
  }
}


class Panels {
  constructor(wizard) {
    this.wizard = wizard;
    this.panelWidth = this.wizard.offsetWidth;
    this.panelsContainer = this.getPanelsContainer();
    this.panels = this.getPanels();
    this.currentStep = 0;

    this.updatePanelsPosition(this.currentStep);
    this.updatePanelsContainerHeight();
  }

  getCurrentPanelHeight() {
    return `${this.getPanels()[this.currentStep].offsetHeight}px`;
  }

  getPanelsContainer() {
    return this.wizard.querySelector('.panels');
  }

  getPanels() {
    return this.wizard.getElementsByClassName('panel');
  }

  updatePanelsContainerHeight() {
    this.panelsContainer.style.height = this.getCurrentPanelHeight();
  }

  updatePanelsPosition(currentStep) {
    const panels = this.panels;
    const panelWidth = this.panelWidth;

    for (let i = 0; i < panels.length; i++) {
      panels[i].classList.remove(
        'movingIn',
        'movingOutBackward',
        'movingOutFoward');


      if (i !== currentStep) {
        if (i < currentStep) panels[i].classList.add('movingOutBackward');
        else
        if (i > currentStep) panels[i].classList.add('movingOutFoward');
      } else {
        panels[i].classList.add('movingIn');
      }
    }

    this.updatePanelsContainerHeight();
  }

  setCurrentStep(currentStep) {
    this.currentStep = currentStep;
    this.updatePanelsPosition(currentStep);
  }
}


class Wizard {
  constructor(obj) {

    this.wizard = obj;
    this.panels = new Panels(this.wizard);
    this.steps = new Steps(this.wizard);
    this.stepsQuantity = this.steps.getStepsQuantity();
    this.currentStep = this.steps.currentStep;

    this.concludeControlMoveStepMethod = this.steps.handleConcludeStep.bind(this.steps);
    this.wizardConclusionMethod = this.handleWizardConclusion.bind(this);

  }

  ajax(options) {
    options = options || {};
    options.type = (options.type || 'GET').toUpperCase();
    options.dataType = options.dataType || 'json';
    var params = this.formatParams(options.data);

    //创建-第一步
    var xhr;
    //非IE6
    if (window.XMLHttpRequest) {
      xhr = new XMLHttpRequest();
    } else {
      //ie6及其以下版本浏览器
      xhr = ActiveXObject('Microsoft.XMLHTTP');
    }

    //接收-第三步
    xhr.onreadystatechange = function () {
      if (xhr.readyState == 4) {
        var status = xhr.status;
        if (status >= 200 && status < 300) {
          options.success && options.success(xhr.responseText, xhr.responseXML);
        } else {
          options.error && options.error(status);
        }
      }
    }

    //连接和发送-第二步
    if (options.type == 'GET') {
      xhr.open('GET', options.url + '?' + params, true);
      xhr.send(null);
    } else if (options.type == 'POST') {
      xhr.open('POST', options.url, true);
      //设置表单提交时的内容类型
      xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      xhr.send(params);
    }
  }

  //格式化参数
  formatParams(data) {
    var arr = [];
    for (var name in data) {
      arr.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]));
    }
    arr.push(('v=' + Math.random()).replace('.', ''));
    return arr.join('&');
  }

  updateButtonsStatus() {

    if (this.currentStep === 0) {
      this.previousControl.classList.add('disabled');
    } else
      this.previousControl.classList.remove('disabled');
  }

  updtadeCurrentStep(movement) {
    this.currentStep += movement;
    this.steps.setCurrentStep(this.currentStep);
    this.panels.setCurrentStep(this.currentStep);

    this.handleNextStepButton();
    this.updateButtonsStatus();
  }

  handleNextStepButton() {
    if (this.currentStep === this.stepsQuantity - 1) {
      this.nextControl.innerHTML = '完成！';
      this.nextControl.removeEventListener('click', this.nextControlMoveStepMethod);
      this.nextControl.addEventListener('click', this.concludeControlMoveStepMethod);
      this.nextControl.addEventListener('click', this.wizardConclusionMethod);
    } else {
      this.nextControl.innerHTML = '下一步';
      this.nextControl.addEventListener('click', this.nextControlMoveStepMethod);
      this.nextControl.removeEventListener('click', this.concludeControlMoveStepMethod);
      this.nextControl.removeEventListener('click', this.wizardConclusionMethod);
    }
  }

  handleWizardConclusion() {
    var host = document.getElementById("host").value;
    var username = document.getElementById("username").value;
    var userpass = document.getElementById("userpass").value;
    var name = document.getElementById("name").value;

    if (host == '' || username == '' || userpass == '' || name == '') {
      console.log(host);
      return;
    }

    var _this = this;

    this.ajax({
      url: '/install',
      type: 'POST',
      dataType: 'json',
      data: {
        name: name,
        host: host,
        username: username,
        userpass: userpass,
      },
      success: function (response, xml) {
        var data = JSON.parse(response);
        if (data.code == '0') {
          _this.wizard.classList.add('completed');
          forward = true;
        } else {
          alert(data.msg)
        }
      },
      error: function (status) {
        //失败后执行的代码
        alert("数据库连接失败！")
      }
    });

    return;
  }

  addControls(previousControl, nextControl) {


    this.previousControl = previousControl;
    this.nextControl = nextControl;
    this.previousControlMoveStepMethod = this.moveStep.bind(this, -1);
    this.nextControlMoveStepMethod = this.moveStep.bind(this, 1);

    previousControl.addEventListener('click', this.previousControlMoveStepMethod);
    nextControl.addEventListener('click', this.nextControlMoveStepMethod);

    this.updateButtonsStatus();
  }

  moveStep(movement) {
    if (this.validateMovement(movement)) {
      this.updtadeCurrentStep(movement);
      this.steps.handleStepsClasses(movement);
    } else {
      throw 'This was an invalid movement';
    }
  }

  validateMovement(movement) {
    const fowardMov = movement > 0 && this.currentStep < this.stepsQuantity - 1;
    const backMov = movement < 0 && this.currentStep > 0;

    return fowardMov || backMov;
  }
}

let forward = false;
let wizardElement = document.getElementById('wizard');
let wizard = new Wizard(wizardElement);
let buttonNext = document.querySelector('.next');
let buttonPrevious = document.querySelector('.previous');

wizard.addControls(buttonPrevious, buttonNext);